package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @author 杨帆
 * @version 1.0
 */
@Slf4j
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;


    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //设置TTL
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    //设置逻辑过期
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){

        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));

    }

    //缓存穿透
    public <R,ID> R queryWithMutex(String keyPrefix, ID id, Class<R>type, Function<ID,R>dbFallback,Long time, TimeUnit unit){
        String key = CACHE_SHOP_KEY+id;
        //1.从redis查询缓存
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(Json)){
            //3.存在，直接返回
            return  JSONUtil.toBean(Json,type);
        }

        if(Json==""){
            return null;
        }

        //4.不存在，根据id查数据库
        R r = dbFallback.apply(id); //根据函数编程，由这个函数去查数据库，然后返回对应的值

        //5.不存在，返回错误
        if(r==null){
            stringRedisTemplate.opsForValue().set(key,"",time, unit);
            return null;
        }
        //6.存在写入redist,30分钟自动过期
       this.set(key,r,time,unit);
        //7.返回
        return r;
    }




    //缓存击穿，逻辑时间判断
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public <R,ID> R queryWithLogicalExpire(String lockprefix,String kryprefix,ID id,Class<R>type,Function<ID,R>dbFallback,Long time, TimeUnit unit){
        String key = kryprefix+id;
        //1.从redis查询缓存
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isBlank(Json)){
            //如果为空（不存在直接返回）
            return null;
        }
        //命中，把json转化为对象
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        JSONObject data = (JSONObject)redisData.getData();
        R r= JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //命中，需要判断过期时间
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回
            return r;
        }


        //过期，需要重建
        //获取锁
        String lockkey =  lockprefix+id;

        boolean flag = tryLock(lockkey);
        if(flag){
            //成功，开启新线程，实现重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                //重建
                try {
                    //先查数据库，在写redis
                    R r1 = dbFallback.apply(id);
                    this.setWithLogicalExpire(key,r1,time,unit);
                    // this.saveShop2Redis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException();
                }finally {
                    unlock(lockkey);
                }
            });
        }

        //失败，返回过期时间
        //释放锁

        //7.返回
        return r;
    }


    //尝试获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

//
//    //逻辑重建
//    public void saveShop2Redis(Long id,Long expireSeconds){
//        //1.查询店铺信息
//        Shop shop = getById(id);
//        RedisData redisData = new RedisData();
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
//    }



}
